package com.cj.startup

import android.os.Process
import com.cj.startup.manager.ExecutorManager
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executor

abstract class AndroidStartup<T> : Startup<T> {

    //入度数初始化，只有依赖的Startup全部执行完才会执行该Startup
    private val mWaitCountDown:CountDownLatch = CountDownLatch(getDependenciesCount())

    override fun dependencies(): MutableList<Class<out Startup<*>>>? = null

    final override fun getDependenciesCount() = dependencies()?.size?:0

    /**
     * 是否在主线程运行
     * 默认在子线程运行
     */
    override fun callCreateOnMainThread(): Boolean = false

    /**
     * 每个任务都可以指定自己执行在哪个线程
     * 默认使用io线程池
     */
    override fun executor(): Executor = ExecutorManager.ioExecutor

    /**
     * 执行线程的优先级
     * 默认最高优先级
     */
    override fun getThreadPriority(): Int = Process.THREAD_PRIORITY_DEFAULT

    final override fun toWait(){
        try {
            mWaitCountDown.await()
        }catch (e: InterruptedException){
            e.printStackTrace()
        }
    }

    final override fun toNotify(){
        mWaitCountDown.countDown()
    }

    /**
     * 是否需要主线程等待该任务执行完成
     * 只有在callCreateOnMainThread方法返回false才有意义
     */
    override fun waitOnMainThread(): Boolean = false

}